using admin.core.Entities.App;
using admin.core.Repositories;
using System.Data;
using Dapper;
using MediatR;
using admin.application.Notifications;

namespace admin.application.Services;

public class AppAuthService
{
    private readonly IRepository<AppUser> _userRepo;
    private readonly IRepository<AppRole> _roleRepo;
    private readonly IAppUserService _userService;
    private readonly IDbConnection _dbConnection;
    private readonly IMediator _mediator;

    public AppAuthService(IRepository<AppUser> userRepo, IRepository<AppRole> roleRepo, IAppUserService userService, IDbConnection dbConnection, IMediator mediator)
    {
        _userRepo = userRepo;
        _roleRepo = roleRepo;
        _userService = userService;
        _dbConnection = dbConnection;
        _mediator = mediator;
    }

    // 用户注册逻辑
    public async Task RegisterAsync(string username, string password)
    {
        // 1. 检查用户名是否存在
        var exists = (await _userRepo.GetAllAsync()).Any(u => u.UserName == username);
        if (exists) throw new Exception("用户名已存在");

        // 2. 生成盐和加密密码
        var salt = Guid.NewGuid().ToString("N");
        var hashedPwd = HashPassword(password, salt);

        // 3. 创建用户
        var user = new AppUser
        {
            UserName = username,
            PassWord = hashedPwd,
            Salt = salt
        };

        user = await _userRepo.AddAsync(user);
        // 发布领域事件
        await _mediator.Publish(new UserRegisteredNotification(new UserRegisteredEvent(user.Id)));
    }

    // 用户登录逻辑
    public async Task<AppUser?> LoginAsync(string username, string password)
    {
        var user = (await _userRepo.GetAllAsync()).FirstOrDefault(u => u.UserName == username);
        if (user == null) return null;

        var hashedPwd = HashPassword(password, user.Salt);
        if (user.PassWord != hashedPwd) return null;

        return user;
    }

    // 用户伪删除逻辑
    public async Task DeleteUserAsync(Guid id)
    {
        var user = (await _userRepo.GetAllAsync()).FirstOrDefault(u => u.Id == id);
        if (user == null) throw new Exception("用户不存在");
        user.IsDeleted = true;
        await _userRepo.UpdateAsync(user);
    }

    private string HashPassword(string password, string salt)
    {
        // 简单示例，实际请用更安全的哈希算法
        using var sha256 = System.Security.Cryptography.SHA256.Create();
        var bytes = System.Text.Encoding.UTF8.GetBytes(password + salt);
        var hash = sha256.ComputeHash(bytes);
        return Convert.ToBase64String(hash);
    }

    private async Task AssignDefaultRoleAsync(Guid userId)
    {
        try
        {
            // 查找默认角色（用户角色）
            var defaultRole = (await _roleRepo.GetAllAsync()).FirstOrDefault(r => r.RoleName == "用户");
            
            if (defaultRole == null)
            {
                // 如果默认角色不存在，创建一个
                defaultRole = new AppRole
                {
                    RoleName = "用户",
                    DataScope = "Self",
                    Code = "USER",
                    IsActived = true,
                    IsDeleted = false,
                    CreatedAt = DateTime.UtcNow,
                    UpdatedAt = DateTime.UtcNow,
                    CreatedBy = userId,
                    UpdatedBy = userId
                };
                
                defaultRole = await _roleRepo.AddAsync(defaultRole);
            }

            // 分配角色给用户
            var sql = "INSERT INTO \"AppRoleAppUser\" (\"UsersId\", \"RolesId\") VALUES (@UserId, @RoleId)";
            await _dbConnection.ExecuteAsync(sql, new { UserId = userId, RoleId = defaultRole.Id });
        }
        catch (Exception ex)
        {
            // 如果角色分配失败，记录日志但不影响用户注册
            Console.WriteLine($"角色分配失败: {ex.Message}");
        }
    }

    // 根据用户ID获取用户信息
    public async Task<AppUser?> GetUserByIdAsync(Guid userId)
    {
        return await _userRepo.GetByIdAsync(userId);
    }
}